package com.ruoyi.system.task;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.ruoyi.system.service.IImageCleanupService;

/**
 * 图片清理定时任务
 * 
 * @author ruoyi
 * @date 2025-01-XX
 */
@Component("imageCleanupTask")
public class ImageCleanupTask 
{
    private static final Logger log = LoggerFactory.getLogger(ImageCleanupTask.class);

    @Autowired
    private IImageCleanupService imageCleanupService;

    /**
     * 每天凌晨2点执行图片清理任务
     */
    @Scheduled(cron = "0 0 2 * * ?")
    public void cleanupUnreferencedImages()
    {
        log.info("开始执行定时图片清理任务...");
        
        try {
            int cleanedCount = imageCleanupService.cleanupUnreferencedImages();
            log.info("定时图片清理任务完成，共清理 {} 个无引用图片", cleanedCount);
        } catch (Exception e) {
            log.error("定时图片清理任务执行失败", e);
        }
    }

    /**
     * 每小时检查一次清理任务状态（可选）
     */
    @Scheduled(cron = "0 0 * * * ?")
    public void checkCleanupStatus()
    {
        String status = imageCleanupService.getCleanupStatus();
        log.debug("图片清理任务状态: {}", status);
    }

    /**
     * 手动触发图片清理任务
     * 供 ImageCleanController 调用
     */
    public void clean()
    {
        log.info("手动触发图片清理任务...");
        
        try {
            int cleanedCount = imageCleanupService.cleanupUnreferencedImages();
            log.info("手动图片清理任务完成，共清理 {} 个无引用图片", cleanedCount);
        } catch (Exception e) {
            log.error("手动图片清理任务执行失败", e);
            throw e;
        }
    }
}
